﻿using Abp.Domain.Repositories;
using Abp.Domain.Services;
using Abp.UI;
using shenghua.Authorization.Users;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace shenghua.Common.Comments
{
    public class CommentManager<T>: DomainService
        where T: Comment
    {
        protected readonly IRepository<T> _repository;

        public CommentManager(
            IRepository<T> repository
            )
        {
            _repository = repository;
        }

        public virtual async Task<T> Get(long? userId, int commentId)
        {
            var query = _repository.GetAll();
            if (userId != null) query = query.Where(r => r.UserId == userId);
            var item = query.Where(r => r.Id == commentId).FirstOrDefault();
            if(item == null)
            {
                throw new UserFriendlyException("不存在的评论");
            }
            return item;
        }

        public virtual async Task<T> MemberEvaluate(Member.Members.Member member, T comment, T parentComment)
        {
            comment.UserId = member.Id;
            comment.UserName = member.UserName;
            comment.UserType = UserType.Member;

            if(parentComment != null)
            {
                comment.ParentCommentId = parentComment.Id;
                comment.TargetId = parentComment.TargetId;
            }

            await _repository.InsertAndGetIdAsync(comment);
            return comment;
        }

        public virtual async Task<T> AdminEvaluate(User user, T comment, T parentComment)
        {
            comment.UserId = user.Id;
            comment.UserName = user.UserName;
            comment.UserType = UserType.Admin;

            if (parentComment != null)
            {
                comment.ParentCommentId = parentComment.Id;
            }

            await _repository.InsertAndGetIdAsync(comment);
            return comment;
        }
        
        public virtual async Task MemberDeleteEvaluate(long memberId, int commentId)
        {
            T comment = _repository.GetAll().Where(r => r.UserType == UserType.Member && r.UserId == memberId && r.Id == commentId).FirstOrDefault();
            if (comment == null)
            {
                throw new UserFriendlyException("要删除的评论不存在或无删除权限");
            }
            await _repository.DeleteAsync(comment);
        }

        public virtual async Task AdminDeleteEvaluate(long adminId, int commentId)
        {
            T comment = _repository.GetAll().Where(r => r.UserType == UserType.Admin && r.UserId == adminId && r.Id == commentId).FirstOrDefault();
            if (comment == null)
            {
                throw new UserFriendlyException("要删除的评论不存在或无删除权限");
            }
            await _repository.DeleteAsync(comment);
        }
    }
}
